package com.qf.controller;

import com.qf.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @PostMapping("/doLogin")
    public Result login(String username, String password,Boolean rememberMe){
        Subject subject = SecurityUtils.getSubject();
        if (password==null){
            password="";
        }

        Md5Hash md5Hash = new Md5Hash(password,username,1024);
        UsernamePasswordToken token = new UsernamePasswordToken(username,md5Hash.toString(),rememberMe);
        try {
            //开始登录
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("未知用户异常");
            e.printStackTrace();
            return Result.error(e.getMessage());
        }catch (LockedAccountException e) {
            System.out.println("账户已锁定");
            e.printStackTrace();
            return Result.error(e.getMessage());
        }catch (CredentialsException e) {
            System.out.println("密码错误");
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

        System.out.println(subject.hasRole("管理员")?"是管理员":"不是管理员");
        System.out.println(subject.isPermitted("sys:user:add") ? "有添加用户的权限":"没有添加用户的权限");
        return Result.ok("登录成功");
    }
    @RequestMapping("/logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok();
    }


    @RequiresRoles(value = {"管理员","开发工程师"},logical = Logical.OR)
    @RequestMapping("/add")
    public Result add(){
        System.out.println("添加");
        return Result.ok();
    }
    @RequiresRoles({"管理员"})
    @RequestMapping("/update")
    public Result update(){
        System.out.println("更新");
        return Result.ok();
    }

    @RequiresPermissions({"sys:user:del"})
    @RequestMapping("/del")
    public Result del(){
        System.out.println("删除");
        return Result.ok();
    }

    @RequiresPermissions({"sys:test:select"})
    @RequestMapping("/select")
    public Result select(){
        System.out.println("查询");
        return Result.ok();
    }

}
